import { isAccessibilityEnabled } from "./autox/accessbility"
import { renderLogin } from "./login"
import { renderQiangBao } from "./qbIndex"
import { httpPost } from "./utils/httpPost"
import { useDeviceUuid } from "./utils/useDeviceUuid"
import { useSetting } from "./utils/useSetting"
import { useStorage } from "./utils/useStorage"
import { renderZbIndex } from "./zbIndex"

function renderMain() {

    const setting = useSetting()
    if (!Array.isArray(setting.type)) {
        setting.type = [
            setting.type
        ].filter(it => !!it)
    }

    ui.layout(`<LinearLayout  layout_width="match_parent" layout_height="match_parent" orientation="vertical" paddingLeft="4sp" paddingRight="4sp">
        <ScrollView layout_width="match_parent" layout_height="wrap_content" paddingTop="4sp">
            <LinearLayout layout_width="match_parent" layout_height="match_parent" orientation="vertical">
                <TextView layout_width="match_parent" layout_height="match_parent" text="权限检查"></TextView>
                <GridLayout id="checkGridLayout" layout_width="match_parent" layout_height="wrap_content" rowCount="1" columnCount="4">
                    <Button layout_height="wrap_content" layout_width="wrap_content" id="auto" text="无障碍"></Button>
                    <Button layout_height="wrap_content" layout_width="wrap_content" id="floaty" text="悬浮窗"></Button>
                    <Button layout_height="wrap_content" layout_width="wrap_content" id="screenCapture" text="截屏"></Button>
                    <Button layout_height="wrap_content" layout_width="wrap_content" id="login" text="登陆"></Button>
                </GridLayout>
                <TextView layout_width="match_parent" layout_height="match_parent" text="功能模块"></TextView>
                <list layout_width="match_parent" layout_height="wrap_content" id="functions">
                    <Button layout_height="wrap_content" id="enter" layout_width="wrap_content" text="{{label}}"></Button>
                </list>
            </LinearLayout>
        </ScrollView>
    </LinearLayout>`)
}

function initView() {
    const checkGridLayoutElement = ui.findView(`checkGridLayout`)
    checkGridLayoutElement.setPadding(10, 10, 10, 10)
    for (let i = 0; i < checkGridLayoutElement.getChildCount(); i++) {
        const child = checkGridLayoutElement.getChildAt(i)
        const params = child.getLayoutParams()
        params.setMargins(10, 10, 10, 10)
        child.setLayoutParams(params)
    }

    const autoElement = ui.findView(`auto`)
    const floatyElement = ui.findView(`floaty`)
    const screenCaptureElement = ui.findView(`screenCapture`)
    const loginElement = ui.findView(`login`)
    const functionsElement = ui.findView(`functions`)

    let hasAutoPermission: boolean = false;
    let hasFloatyPermission: boolean = false;
    let hasScreenCapturePermission: boolean = false;
    let hasLogin: boolean = false;

    autoElement.on('click', () => {
        threads.start(() => {
            auto.waitFor()
            checkPermission()
        })
    })

    floatyElement.on('click', () => {
        threads.start(() => {
            if (!floaty.checkPermission()) {
                floaty.requestPermission()
            }
            checkPermission();
        })
    })

    screenCaptureElement.on('click', () => {
        threads.start(() => {
            requestScreenCapture()
            checkPermission();
        })
    })

    loginElement.on('click', () => {
        renderLogin()
    })

    const functions: any = {
        qiangbao: {
            label: '抢包',
            id: 'qiangbao',
            click: () => {
                if (!hasAutoPermission) {
                    toastLog(`请设置无障碍权限`)
                    return;
                }
                if (!hasFloatyPermission) {
                    toastLog(`请设置悬浮窗权限`)
                    return;
                }
                if (!hasScreenCapturePermission) {
                    toastLog(`请设置截幕权限`)
                    return;
                }
                if (!hasLogin) {
                    toastLog(`请先登陆`)
                    return;
                }
                renderQiangBao()
            }
        },
        zhuabao: {
            label: '抓包',
            id: 'zhuabao',
            click: () => {
                // 检查权限
                if (!hasAutoPermission) {
                    toastLog(`请设置无障碍权限`)
                    return;
                }
                if (!hasFloatyPermission) {
                    toastLog(`请设置悬浮窗权限`)
                    return;
                }
                if (!hasScreenCapturePermission) {
                    toastLog(`请设置截幕权限`)
                    return;
                }
                if (!hasLogin) {
                    toastLog(`请先登陆`)
                    return;
                }
                renderZbIndex()
            }
        }
    }

    function checkPermission() {

        ui.run(() => {
            if (isAccessibilityEnabled()) {
                autoElement.attr('bg', '#03c362')
                autoElement.setTextColor(colors.parseColor('#ffffff'))
                hasAutoPermission = true;
                console.log(`无障碍服务已启动`)
            }
            if (floaty.checkPermission()) {
                floatyElement.attr('bg', '#03c362')
                floatyElement.setTextColor(colors.parseColor('#ffffff'))
                hasFloatyPermission = true;
                console.log(`悬浮窗权限已获得`)
            }

            try {
                const img = captureScreen()
                if (img) {
                    screenCaptureElement.attr('bg', '#03c362')
                    screenCaptureElement.setTextColor(colors.parseColor('#ffffff'))
                    hasScreenCapturePermission = true;
                    console.log(`截图权限已获得`)
                }
            } catch (e) {
            }
        })

        threads.start(() => {
            try {
                const setting = useSetting()
                const res = httpPost('client/register', { uuid: useDeviceUuid() })
                if (res.owner) {
                    hasLogin = true
                    const modules = httpPost('client/loadModules', { uuid: useDeviceUuid() })
                    setting.modules = modules;
                    ui.run(() => {
                        loginElement.attr('bg', '#03c362')
                        loginElement.setTextColor(colors.parseColor('#ffffff'))
                        const functionsModules = setting.modules.map((module) => functions[module]).filter(it => !!it)
                        functionsElement.setDataSource(functionsModules);
                        functionsElement.on("item_click", (item: any, i: number, itemView: any, listView: any) => {
                            toast("被点击的人名字为: " + item.name + "，年龄为: " + item.age);
                        });
                        functionsElement.on("item_bind", (itemView: any, itemHolder: any) => {
                            itemView.enter.on('click', () => {
                                const item = itemHolder.item;
                                const click = item.click;
                                if (click) click()
                            })
                        });
                    })
                    useStorage().put('setting', setting);
                } else {
                    setting.id = res.id;
                    setting.mobile = res.mobile;
                    useStorage().put('setting', setting);
                }
            } catch (e) {
                console.log(e)
            }
        })
    }
    checkPermission()
}

renderMain()
initView()